<template>
    <div class="app-container flex-cloumn" v-loading="loading">
        <el-drawer v-model="drawer2" :direction="direction" title='期权簿记' size="90%" destroy-on-close
                   v-loading="loading">
            <template #default>
                <el-row :style="{height:screenHeight}">
                    <el-col :span="5">
                        <!--交易要素-->
                        <el-card class="tradeCard">
                            <template #header>
                                <div>
                                    <span>交易要素</span>
                                </div>
                            </template>
                            <el-form ref="dialog2DocumentForm" :model="instrument2TradeFrom.data"
                                     :rules="dialog2DocumentFormRules" label-width="100px">
                                <el-form-item label="本方账户" prop="accId">
                                    <baseCombox url="/trade/account/querySelfAccountCombox.action"
                                                clearable
                                                valueField="accId"
                                                labelField="accName"
                                                size="small"
                                                v-model="instrument2TradeFrom.data.accId"
                                                :style="{width: '100%'}" placeholder="本方账户"></baseCombox>
                                </el-form-item>
                                <el-form-item label="交易对手" prop="partyId">
                                    <baseCombox v-model="instrument2TradeFrom.data.partyId"
                                                clearable
                                                labelField="partyName"
                                                url="/trade/counterparty/queryCounterparty4Combox.action"
                                                size="small"
                                                valueField="partyId"
                                                :style="{width: '100%'}" placeholder="对手"></baseCombox>
                                </el-form-item>
                                <el-form-item label="产品编号" prop="extTradeId">
                                    <el-input v-model="instrument2TradeFrom.data.extTradeId" maxlength="100"
                                              autocomplete="off"></el-input>
                                </el-form-item>
                                <el-form-item label="合约编号" prop="iCode">
                                    <el-input v-model="instrument2TradeFrom.data.iCode" maxlength="100"
                                              autocomplete="off"></el-input>
                                </el-form-item>
                                <el-form-item label="交易日期" prop="tradeDate">
                                    <el-date-picker v-model="instrument2TradeFrom.data.tradeDate" placeholder="选择日期"
                                                    type="date"
                                                    value-format="YYYY-MM-DD">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="期初保证金" prop="margin" v-show="false">
                                    <el-row style="width: 100%;">
                                        <el-col :span="6">
                                            <el-select v-model="instrument2TradeFrom.data.marginDirection"
                                                       placeholder="请选择">
                                                <el-option label="支付" value="-1"/>
                                                <el-option label="收取" value="1"/>
                                            </el-select>
                                        </el-col>
                                        <el-col :span="18">
                                            <InputAmount v-model:value="instrument2TradeFrom.data.margin" maxlength="20"
                                                         append="元"
                                                         autocomplete="off"
                                                         precision="2"/>
                                        </el-col>
                                    </el-row>
                                </el-form-item>
                                <el-form-item label="前端费支付方向" prop="frontFee">
                                    <el-select v-model="instrument2TradeFrom.data.frontFeeDirection"
                                               placeholder="请选择" style="width:100%">
                                        <el-option label="支付" value="-1"/>
                                        <el-option label="收取" value="1"/>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="前端费" prop="frontFee">
                                    <el-row style="width: 100%;">
                                        <el-col :span="10">
                                            <el-checkbox v-model="instrument2TradeFrom.data.frontFeeYear"
                                                         @change="onfrontFeeRateChange()"
                                                         name="status" false-label="0" true-label="1">年化
                                            </el-checkbox>
                                        </el-col>

                                        <el-col :span="14">
                                            <Numberinput v-model="instrument2TradeFrom.data.frontFeeRate"
                                                         :max="1000000000" :min="0"
                                                         append="%" width="100%"
                                                         precision="2" @blur="onfrontFeeRateChange()"/>
                                        </el-col>
                                    </el-row>
                                    <el-row style="width: 100%;">
                                        <InputAmount v-model:value="instrument2TradeFrom.data.frontFee" maxlength="20"
                                                     append="元" width="100%"
                                                     autocomplete="off" @blur="onfrontFeeChange()"
                                                     precision="2"/>
                                    </el-row>
                                </el-form-item>
                                <el-form-item label="前端费支付日" prop="frontFeePaydate">
                                    <el-date-picker v-model="instrument2TradeFrom.data.frontFeePaydate"
                                                    placeholder="选择日期" type="date"
                                                    value-format="YYYY-MM-DD">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="期权费支付方向" prop="fee">
                                    <el-select v-model="instrument2TradeFrom.data.feeDirection" style="width:100%"
                                               placeholder="请选择">
                                        <el-option label="支付" value="-1"/>
                                        <el-option label="收取" value="1"/>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="期权费" prop="fee">
                                    <el-row style="width: 100%;">
                                        <el-col :span="10">
                                            <el-checkbox v-model="instrument2TradeFrom.data.feeYear"
                                                         @change="onFeeRateChange()" name="status"
                                                         false-label="0" true-label="1">年化
                                            </el-checkbox>
                                        </el-col>
                                        <el-col :span="14">
                                            <Numberinput v-model="instrument2TradeFrom.data.feeRate" :max="1000000000"
                                                         :min="0" append="%"
                                                         width="100%"
                                                         precision="2" @blur="onFeeRateChange()"/>
                                        </el-col>
                                    </el-row>
                                    <el-row style="width: 100%;">
                                        <InputAmount v-model:value="instrument2TradeFrom.data.fee" maxlength="20"
                                                     append="元" width="100%"
                                                     autocomplete="off" @blur="onFeeChange()"
                                                     precision="2"/>
                                    </el-row>
                                </el-form-item>
                                <el-form-item label="期权费支付日">
                                    <el-date-picker v-model="instrument2TradeFrom.data.setDate" placeholder="选择日期"
                                                    type="date"
                                                    value-format="YYYY-MM-DD">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="提前终止日期" prop="terminateDate" v-show="false">
                                    <el-date-picker v-model="instrument2TradeFrom.data.terminateDate"
                                                    placeholder="选择日期" type="date"
                                                    value-format="YYYY-MM-DD">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="提前终止费用" prop="terminateFee" v-show="false">
                                    <InputAmount v-model:value="instrument2TradeFrom.data.terminateFee" maxlength="20"
                                                 append="元"
                                                 autocomplete="off"
                                                 precision="2"/>
                                </el-form-item>
                                <el-form-item label="备注" prop="remark">
                                    <el-input v-model="instrument2TradeFrom.data.remark" maxlength="300"
                                              autocomplete="off"
                                              type="textarea"></el-input>
                                </el-form-item>
                                <!--                <el-form-item style="display: inline-block ;margin-top: 1rem;">
                                                  <el-button type="primary" @click="saveTrade">保存</el-button>
                                                  &lt;!&ndash;             <el-button>Cancel</el-button>&ndash;&gt;
                                                </el-form-item>-->
                            </el-form>
                        </el-card>
                    </el-col>
                    <el-col :span="19">
                        <!--条款要素-->
                        <el-card class="instrumentCard">
                            <template #header>
                                <div>
                                    <span>交易条款</span>
                                </div>
                            </template>
                            <div>
                                <el-form :inline="true" class="demo-form-inline">
                                    <el-form-item>
                                        <el-dropdown class="right-menu-item hover-effect" trigger="click">
                                            <div class="avatar-wrapper">
                                                <el-button type="primary"
                                                           v-show="status != 'update'"
                                                           plain icon="Plus"
                                                           v-hasPermi="['trade:otcoptiontrade:basestructure']"
                                                           size="small">基础结构
                                                </el-button>
                                            </div>
                                            <template #dropdown>
                                                <el-dropdown-menu>
                                                    <el-dropdown-item
                                                            v-for="item in OptionList"
                                                            :key="item.value"
                                                            :label="item.label"
                                                            :value="item.value"
                                                            @click="createNode(item.value)"
                                                    >{{ item.label }}
                                                    </el-dropdown-item>
                                                </el-dropdown-menu>
                                            </template>
                                        </el-dropdown>
                                    </el-form-item>
                                    <el-form-item label="计算日期">
                                        <el-date-picker
                                                v-model="calcPricingParam.valueDate"
                                                type="date"
                                                value-format="YYYY-MM-DD"
                                                placeholder="选择日期">
                                        </el-date-picker>
                                    </el-form-item>
                                    <el-form-item label="定价环境" prop="cfgId">
                                        <baseCombox
                                                url="/pricing/comboBox/queryPriceCfg4Local.action?productType=OtcOption"
                                                ref="cfgIdRef"
                                                clearable
                                                valueField="cfgId"
                                                labelField="name"
                                                size="small"
                                                @defaultSelect="(value) => {calcPricingParam.cfgId = value}"
                                                :defaultSelectIndex="'0'"
                                                style="width: 240px" placeholder="定价配置"
                                                v-model="calcPricingParam.cfgId"></baseCombox>
                                    </el-form-item>
                                    <el-form-item>
                                        <el-button type="primary" @click="submitAll"
                                                   v-hasPermi="['trade:otcoptiontrade:calAll']">计算
                                        </el-button>
                                        <el-button type="danger" :icon="Delete" @click="delAll"
                                                   v-show="status != 'update'"
                                                   v-hasPermi="['trade:otcoptiontrade:removeAll']">清除全部
                                        </el-button>
                                    </el-form-item>
                                </el-form>
                                <div>
                                    <div class="instrumentList" v-for="(v,i) in instruments" v-bind:key="i"
                                         style="display: inline-flex;margin: 3px 0px 0px 0px;">
                                        <component :is="getInstrument(instruments[i].optionType)"
                                                   :del="del" :calc="submit"
                                                   :copy="copy" :useType="'trade'"
                                                   :ref="'instrument'+instruments[i].index"
                                                   :setformData="setformData"
                                                   :formData="instruments[i].formData"
                                                   :index="instruments[i].index"
                                                   :cfgId="instruments[i].cfgId"
                                                   :getDefaultCfg="getDefaultCfg"
                                                   :save2Trade="OpenDialog2Document"
                                                   :save2CalcLog="OpenDialog2CalcLog"
                                                   :calcPricingParam="instruments[i].calcPricingParam"
                                                   :valueDate="calcPricingParam.valueDate"
                                                   :cacheFormData="()=>{}"
                                                   :result="instruments[i].result"/>
                                    </div>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="cancelClick">关闭</el-button>
                    <el-button type="primary" @click="saveTrade">提交</el-button>
                </div>
            </template>
        </el-drawer>
        <el-form :model="queryParams" ref="queryRef" v-show="showSearch" label-width="65px">
            <el-row :gutter="12">
                <el-col :span="6">
                    <el-form-item label="合约编号">
                        <el-input
                                clearable
                                size="small"
                                :style="{width: '100%'}"
                                @bulr="handleQuery"
                                placeholder="合约编号"
                                v-model="queryParams.iCodeCond"
                        />

                    </el-form-item>
                </el-col>

        <el-col :span="6">
          <el-form-item label="挂钩标的" prop="instrument">
            <baseCombox url="/marketdata/instrument/getInstruments.action" clearable
                        size="small"
                        multiple collapse-tags collapse-tags-tooltip
                        valueField="code"
                        labelField="productName" placeholder="挂钩标的"
                        v-model="queryParams.instruments"></baseCombox>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="起始日">
            <el-date-picker
                v-model="queryParams.begDate1"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="-">
            <el-date-picker
                v-model="queryParams.begDate2"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="6">
          <el-form-item label="本方账户" prop="accIds">
            <baseCombox url="/trade/account/querySelfAccountCombox.action" clearable
                        size="small"
                        multiple collapse-tags collapse-tags-tooltip
                        valueField="accId"
                        labelField="accName" placeholder="本方账户"
                        v-model="queryParams.accIds"></baseCombox>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="期权类型">
            <dictCombox v-model="queryParams.optionTypes" collapse-tags collapse-tags-tooltip multiple
                        dictType="optionType" size="small"></dictCombox>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="到期日">
            <el-date-picker
                v-model="queryParams.endDate1"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="-">
            <el-date-picker
                v-model="queryParams.endDate2"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="6">
          <el-form-item label="行权方式" prop="exerciseType">
            <dictCombox v-model="queryParams.exerciseType" :style="{width: '100%'}" dictType="exerciseType"
                        size="small"></dictCombox>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="期权状态" prop="eventStatuss">
            <dictCombox v-model="queryParams.eventStatuss" multiple collapse-tags collapse-tags-tooltip
                        dictType="durationStatus" size="small"></dictCombox>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="交易日期">
            <el-date-picker
                v-model="queryParams.tradeDate1"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="-">
            <el-date-picker
                v-model="queryParams.tradeDate2"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="交易对手" prop="partyIds">
            <baseCombox url="/trade/counterparty/queryCounterparty4Combox.action" clearable
                        :style="{width: '100%'}"
                        size="small"
                        multiple collapse-tags collapse-tags-tooltip
                        valueField="partyId" labelField="partyName" placeholder="交易对手"
                        v-model="queryParams.partyIds"></baseCombox>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="交易类型">
            <dictCombox v-model="queryParams.tradeTypes" collapse-tags collapse-tags-tooltip
                        filterKey="OtcOptionSell,OtcOptionBuy"
                        dictType="tradeType" size="small"></dictCombox>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="买卖方向" prop="payDirection">
            <dictCombox v-model="queryParams.payDirection" dictType="payDirection" size="small"></dictCombox>
          </el-form-item>
        </el-col>


        <el-col :span="6">
          <el-form-item>
            <el-button icon="Search" size="small" style="margin: 3px 3px" type="primary"
                       v-hasPermi="['trade:otcoptiontrade:list']"
                       @click="handleQuery">搜索
            </el-button>

            <el-button icon="ArrowRight" size="small" style="margin: 3px 3px" type="primary" :disabled="single"
                       v-hasPermi="['trade:otcoptiontrade:pric']"
                       @click="handlePricing">定价
            </el-button>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row :gutter="12" >
        <el-col :span="16">
            <el-button type="primary" size="small" style="margin: 3px 3px" @click="openDetailInsert" icon="Plus"
                       v-hasPermi="['trade:otcoptiontrade:add']">
              新增
            </el-button>
            <el-button type="success" icon="Edit" size="small" style="margin: 3px 3px" @click="openDetailUpdate"
                       :disabled="single"
                       v-hasPermi="['trade:otcoptiontrade:upt']">
              修改
            </el-button>

            <el-button icon="Delete" size="small" style="margin: 3px 3px" type="danger" :disabled="single"
                       v-hasPermi="['trade:otcoptiontrade:delete']"
                       @click="handleDelete">删除
            </el-button>

<!--            <el-button-->
<!--                type="warning"-->
<!--                style="margin: 3px 3px"-->
<!--                icon="Download"-->
<!--                size="small"-->
<!--                @click="handleExport"-->
<!--                v-hasPermi="['trade:otcoptiontrade:export']"-->
<!--            >当页导出-->
<!--            </el-button>-->
            <el-button
                type="warning"
                style="margin: 3px 3px"
                icon="Download"
                size="small"
                @click="handleExportAll"
                v-hasPermi="['trade:otcoptiontrade:export']"
            >导出
            </el-button>
            <el-dropdown class="right-menu-item hover-effect" trigger="click">
              <div class="avatar-wrapper">
                <el-button
                    type="warning"
                    plain
                    icon="Download"
                    style="margin: 3px 3px"
                    v-hasPermi="['trade:otcoptiontrade:import']"
                    size="small"
                >导入
                </el-button>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <!--              <el-dropdown-item-->
                  <!--                  v-for="item in OptionList"-->
                  <!--                  @click="handleImport(item.value)"-->
                  <!--              >{{item.label}}</el-dropdown-item>-->
                  <el-dropdown-item @click="handleImport('Option')">Option导入</el-dropdown-item>
                  <el-dropdown-item @click="handleImport('Must')">Must导入</el-dropdown-item>
                </el-dropdown-menu>
                <!--              <el-dropdown-menu>-->
                <!--                <el-dropdown-item @click="handleImport('Vanilla')">香草期权</el-dropdown-item>-->
                <!-- <el-dropdown-item @click="handleImport('Digital')">二元期权</el-dropdown-item> -->
                <!--                <el-dropdown-item @click="handleImport('DoubleDigital')">双层二元</el-dropdown-item>-->
                <!--                <el-dropdown-item @click="handleImport('MultiDigital')">三层阶梯</el-dropdown-item>-->
                <!--                <el-dropdown-item @click="handleImport('Touch')">触碰期权</el-dropdown-item>-->
                <!--                <el-dropdown-item @click="handleImport('SingleSharkFin')">单鲨期权</el-dropdown-item>-->
                <!--                <el-dropdown-item @click="handleImport('DoubleShark')">双鲨期权</el-dropdown-item>-->
                <!--                <el-dropdown-item @click="handleImport('doubleBarrier')">双障碍期权</el-dropdown-item>-->
                <!--                <el-dropdown-item @click="handleImport('RangeAccrual')">区间累计期权</el-dropdown-item>-->
                <!--                <el-dropdown-item @click="handleImport('BasicSnowball')">保本雪球</el-dropdown-item>-->
                <!--                <el-dropdown-item @click="handleImport('Option')">Option导入</el-dropdown-item>-->
                <!--                <el-dropdown-item @click="handleImport('Must')">Must导入</el-dropdown-item>-->
                <!--              </el-dropdown-menu>-->
              </template>
            </el-dropdown>
        </el-col>
        <el-col :span="2">
          <div/>
        </el-col>
        <el-col :span="4">


        </el-col>


      </el-row>
    </el-form>

    <xTable ref="refTradeBalanceTable" v-loading="loading" :data="tradeList" @row-dblclick="handleDbclick"
            class="tableDragger_form"
            border
            multiple="true"
            @selection-change="TradeBalanceTableSelect"
            refId="refTradeBalanceTable">

      <template #columList>
        <el-table-column label="序号" align="center" type="index" width="auto">
        </el-table-column>
        <el-table-column align="center" label="产品编号" prop="extTradeId" width="200"/>
        <el-table-column align="center" label="合约编号" prop="iCode" width="200"/>
        <el-table-column align="center" label="期权类型" prop="productType" width="auto">
          <template #default="scope">
            <dict-tag spVal="*" :options="optionType" :value="scope.row.productType"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="交易日期" prop="tradeDate" width="auto"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="标的代码" prop="uICode" width="auto"/>
        <el-table-column align="center" label="标的名称" prop="uIName" width="100px"/>
        <el-table-column v-if="false" align="center" label="资产类型" prop="uAType" width="auto"/>
        <el-table-column v-if="false" align="center" label="市场类型" prop="uMType" width="auto"/>
        <el-table-column align="center" label="买卖方向" prop="payDirection" width="auto">
          <template #default="scope">
            <dict-tag :options="payDirection" :value="scope.row.payDirection"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="涨跌类型" prop="optionType" width="auto">
          <template #default="scope">
            <dict-tag :options="callPut" :value="scope.row.optionType"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="行权方式" prop="exerciseType" width="auto">
          <template #default="scope">
            <dict-tag :options="exerciseType" :value="scope.row.exerciseType"/>
          </template>
        </el-table-column>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="高行权价(元)" prop="strikePrice"
                         width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="低行权价(元)" prop="lowStrikePrice"
                         width="100px"/>
        <el-table-column :formatter="formartEmptyTablePercentP2" align="right" label="收益率1(%)" prop="yield1"
                         width="100px"/>
        <el-table-column :formatter="formartEmptyTablePercentP2" align="right" label="收益率2(%)" prop="yield2"
                         width="100px"/>
        <el-table-column :formatter="formartEmptyTablePercentP2" align="right" label="收益率3(%)" prop="yield3"
                         width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="障碍价1(元)" prop="triggerPrice1"
                         width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="障碍价2(元)" prop="triggerPrice2"
                         width="100px"/>
        <el-table-column :formatter="(row, column, cellValue)=>{return Boolean(cellValue=='1')?'是':'否'}" align="right"
                         label="期权费年化" prop="frontOptionFeeYear" width="120px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="期权费率(%)" prop="frontOptionFeeRate"
                         width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="期权费(元)" prop="frontOptionFee"
                         width="100px"/>
        <el-table-column align="center" label="期权费支付日" prop="frontOptionFeePaydate" width="120px"/>

        <el-table-column :formatter="(row, column, cellValue)=>{return Boolean(cellValue=='1')?'是':'否'}" align="right"
                         label="前端费年化" prop="frontFeeYear" width="120px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="前端费率(%)" prop="frontFeeRate"
                         width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="前端费(元)" prop="frontFee" width="100px"/>
        <el-table-column align="center" label="前端费支付日" prop="frontFeePaydate" width="100px"/>

        <el-table-column align="center" label="起始日" prop="issueDate" width="100px"/>
        <el-table-column align="center" label="到期日" prop="maturityDate" width="100px"/>
        <el-table-column align="center" label="到期支付日" prop="paymentDate" width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="提前终止费用(元)" prop="terminateFee"
                         width="120px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="期初价格" prop="price" width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="名义本金(元)" prop="volume" width="100px"/>
        <el-table-column :formatter="formartEmptyTablePercentP2" align="right" label="参与率1(%)" prop="participationRate1"
                         width="100px"/>
        <el-table-column :formatter="formartEmptyTablePercentP2" align="right" label="参与率2(%)" prop="participationRate2"
                         width="100px"/>
        <!--          <el-table-column :formatter="formartEmptyTablePercentP2" align="right" label="固定利率(%)" prop="fixedRate" width="100px"/>-->
        <el-table-column align="center" label="期权状态" prop="eventStatus" width="auto">
          <template #default="scope">
            <dict-tag :options="durationStatus" :value="scope.row.eventStatus"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="交易对手" prop="partyName" width="100px"/>
        <el-table-column align="center" label="本方账户" prop="accName" width="100px"/>
        <el-table-column align="center" label="version" prop="version" width="100px" v-if="false"/>

        <el-table-column align="center">
          <template #default="scope">
            <el-button size="small" @click="openDetail(scope.$index, scope.row)"
            >详情
            </el-button>
          </template>
        </el-table-column>
      </template>
    </xTable>
    <pagination

        v-show="total > 0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getTradeList"
    />
    <el-dialog v-model="InstrumentDialogVisible" title="交易详情" width="720px" destroy-on-close="true"
               :close-on-click-modal="false">
      <el-row>
        <el-col span="8">
          <el-card shadow="hover" style="width: 350px;height:100%;margin:3px 0 3px 0;">
            <template #header>
              <div class="option-header">
                <div class="option-header-content"><span>交易要素</span></div>
                <div>

                </div>
              </div>
            </template>
            <div class="optionst01">
              <el-form ref="dialog2DocumentForm" :model="InstrumentDialogInstrument.data" size="small" label-width="120px" disabled>
                <el-form-item label="本方账户" prop="accId">
                  <baseCombox url="/trade/account/querySelfAccountCombox.action"
                              clearable
                              valueField="accId"
                              labelField="accName"
                              size="small"
                              v-model="InstrumentDialogInstrument.data.accId"
                              :style="{width: '100%'}" placeholder=""></baseCombox>
                </el-form-item>
                <el-form-item label="交易对手" prop="partyId">
                  <baseCombox v-model="InstrumentDialogInstrument.data.partyId"
                              clearable
                              labelField="partyName"
                              url="/trade/counterparty/queryCounterparty4Combox.action"
                              size="small"
                              valueField="partyId"
                              placeholder=" "></baseCombox>
                </el-form-item>
                <el-form-item label="产品编号" prop="extTradeId">
                  <el-input v-model="InstrumentDialogInstrument.data.extTradeId" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="合约编号" prop="iCode">
                  <el-input v-model="InstrumentDialogInstrument.data.iCode" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="交易日期" prop="tradeDate">
                  <el-date-picker v-model="InstrumentDialogInstrument.data.tradeDate" placeholder="选择日期" type="date"
                                  value-format="YYYY-MM-DD">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="期初保证金" prop="margin" v-show="false">
                  <el-row style="width: 100%;">
                    <el-col :span="6">
                      <el-select v-model="InstrumentDialogInstrument.data.amountDirection" placeholder="请选择">
                        <el-option label="支付" value="-1"/>
                        <el-option label="收取" value="1"/>
                      </el-select>
                    </el-col>
                    <el-col :span="18">
                      <InputAmount v-model:value="InstrumentDialogInstrument.data.amount" append="元"
                                   precision="2"/>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item label="前端费支付方向" prop="frontFee">
                  <el-select v-model="InstrumentDialogInstrument.data.frontFeeDirection" placeholder="请选择">
                    <el-option label="支付" value="-1"/>
                    <el-option label="收取" value="1"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="前端费" prop="frontFee">
                  <el-row style="width: 100%;">
                    <el-col :span="10">
                      <el-checkbox v-model="InstrumentDialogInstrument.data.frontFeeYear"
                                   @change="onfrontFeeRateChange()" name="status" false-label="0" true-label="1">年化
                      </el-checkbox>
                    </el-col>

                    <el-col :span="14">
                      <Numberinput v-model="InstrumentDialogInstrument.data.frontFeeRate" :max="1000000000" :min="0"
                                   append="%" width="100%"
                                   precision="2" @blur="onfrontFeeRateChange()"/>
                    </el-col>
                  </el-row>
                  <el-row style="width: 100%;">
                    <InputAmount v-model:value="InstrumentDialogInstrument.data.frontFee" maxlength="20" append="元"
                                 width="100%"
                                 autocomplete="off" @blur="onfrontFeeChange()"
                                 precision="2"/>
                  </el-row>
                </el-form-item>
                <el-form-item label="前端费支付日" prop="frontFeePaydate">
                  <el-date-picker v-model="InstrumentDialogInstrument.data.frontFeePaydate" placeholder="选择日期"
                                  type="date"
                                  value-format="YYYY-MM-DD">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="期权费支付方向" prop="fee">
                  <el-select v-model="InstrumentDialogInstrument.data.feeDirection" placeholder="请选择">
                    <el-option label="支付" value="-1"/>
                    <el-option label="收取" value="1"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="期权费" prop="fee">
                  <el-row style="width: 100%;">
                    <el-col :span="10">
                      <el-checkbox v-model="InstrumentDialogInstrument.data.feeYear" @change="onFeeRateChange()"
                                   name="status" false-label="0" true-label="1">年化
                      </el-checkbox>
                    </el-col>
                    <el-col :span="14">
                      <Numberinput v-model="InstrumentDialogInstrument.data.feeRate" :max="1000000000" :min="0"
                                   append="%" width="100%"
                                   precision="2" @blur="onFeeRateChange()"/>
                    </el-col>
                  </el-row>
                  <el-row style="width: 100%;">
                    <InputAmount v-model:value="InstrumentDialogInstrument.data.fee" maxlength="20" append="元" width="100%"
                                 autocomplete="off" @blur="onFeeChange()"
                                 precision="2"/>
                  </el-row>
                </el-form-item>
                <el-form-item label="期权费支付日" prop="setDate">
                  <el-date-picker v-model="InstrumentDialogInstrument.data.setDate" placeholder="" type="date"
                                  value-format="YYYY-MM-DD">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="提前终止日期" prop="terminateDate" v-show="false">
                  <el-date-picker v-model="InstrumentDialogInstrument.data.terminateDate" placeholder="选择日期" type="date"
                                  value-format="YYYY-MM-DD">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="提前终止费用" prop="terminateFee" v-show="false">
                  <InputAmount v-model:value="InstrumentDialogInstrument.data.terminateFee" append="元"
                               autocomplete="off"
                               precision="2"/>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="InstrumentDialogInstrument.data.remark" autocomplete="off"
                            type="textarea"></el-input>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </el-col>
        <el-col span="16">
          <detail :close="closeInstrumentDialog" :instrument="InstrumentDialogInstrument.data"/>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog :close-on-click-modal="false"
               draggable="true"
               :title="tradeTitle"
               v-model="simpleOpen"
               destroy-on-close="true"
               width="630px"
               append-to-body>
      <el-form ref="tradeFromRef">
        <el-form-item label="交易类型">
          <dictCombox v-model="tradeFrom.tradeType" dictType="simpleTradeType" clearable :disabled="disableFlag"
                      style="width:225px"
                      size="small">
          </dictCombox>
          <el-form-item label="本方账户" label-width="auto">
            <baseCombox v-model="tradeFrom.accId"
                        :disabled="disableFlag"
                        :style="{width: '100%'}"
                        clearable
                        labelField="accName"
                        placeholder="本方账户"
                        size="small"
                        style="width:225px"
                        url="/trade/account/querySelfAccountCombox.action" valueField="accId"></baseCombox>
          </el-form-item>
        </el-form-item>
        <el-form-item label="交易日期">
          <el-date-picker
              v-model="tradeFrom.tradeDate"
              :disabled="disableFlag"
              placeholder="选择交易日期"
              size="small"
              style="width:225px"
              type="date"
              value-format="YYYY-MM-DD">
          </el-date-picker>
          <el-form-item label="标的" label-width="auto" prop="instrumenId">
            <underlyer ref="underlyerIdRef" v-model="tradeFrom.instrumenId" :disabled="disableFlag"
                       :underlyerId="tradeFrom.instrumenId" style="width:225px"/>
          </el-form-item>
        </el-form-item>
        <el-form-item label="数量" label-width="auto">
          <InputAmount v-model:value="tradeFrom.volume" style="width:225px" :disabled="disableFlag"></InputAmount>
          <el-form-item label="价格" label-width="auto">
            <InputAmount v-model:value="tradeFrom.price" :disabled="disableFlag" style="width:225px" append="元"
            ></InputAmount>
          </el-form-item>
        </el-form-item>
        <el-form-item label="金额" label-width="auto">
          <el-select v-model="tradeFrom.amountDirection" :disabled="disableFlag" placeholder="请选择" style="width:60px">
            <el-option label="支付" value="-1"/>
            <el-option label="收取" value="1"/>
          </el-select>
          <el-form-item>
            <InputAmount :disabled="disableFlag" v-model="tradeFrom.amount" style="width:165px" append="元"
            ></InputAmount>
          </el-form-item>
          <el-form-item label="费用" label-width="auto">
            <el-select :disabled="disableFlag" v-model="tradeFrom.feeDirection" placeholder="请选择" style="width:60px">
              <el-option label="支付" value='-1'/>
              <el-option label="收取" value='1'/>
            </el-select>
            <el-form-item>
              <InputAmount :disabled="disableFlag" v-model="tradeFrom.fee" style="width:165px"
                           append="元"></InputAmount>
            </el-form-item>
          </el-form-item>
        </el-form-item>
        <el-form-item label="备注" label-width="auto">
          <el-input :disabled="disableFlag" v-model="tradeFrom.remark" :autosize="{ minRows: 4, maxRows: 100 }"
                    style="width:550px"
                    type="textarea"/>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="upload.title" :close-on-click-modal="false" draggable="true" v-model="upload.open" width="400px"
               append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="100"
          drag
          multiple
          :file-list="fileList"
          accept=".csv"
          :headers="upload.headers"
          :action="upload.newurl"
          :disabled="upload.isUploading"
          :before-upload="beforeUpload"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          :on-exceed="exceedLimit"
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text" @click="uploadFile" >将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__text" @click="uploadFolder" >上传文件夹<em>点击上传文件夹</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <!--            <div class="el-upload__tip">-->
            <!--              <el-checkbox v-model="upload.updateSupport"/>-->
            <!--              是否更新已经存在的用户数据-->
            <!--            </div>-->
            <span>仅允许导入csv格式文件。上传文件数量限制100个</span>
<!--            <el-link type="primary" :underline="false"-->
<!--                     style="font-size:12px;vertical-align: baseline;"-->
<!--                     @click="downTemplate">下载模板-->
<!--            </el-link>-->
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="downTemplate" >下载模板</el-button>
          <el-button type="primary"
                     @click="submitFileForm"
          >确定上传
          </el-button>
          <el-button @click="cancelUpload" >取消上传</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Otcoptiontrade">
import {getOptionList, getInstrument} from "@/views/calc/otcOtion/instrument/common/common";
import {defineAsyncComponent, getCurrentInstance, onMounted, reactive, ref, watch, provide} from 'vue'
import {formartFormP4, unFormartNumber, numberPrecision} from '@/utils/numberUtil'
import baseCombox from '@/xquant/base/baseCombox'
import InputAmount from '@/xquant/base/InputAmount'
import Numberinput from '@/xquant/base/number'
import detail from '@/views/calc/otcOtion/pricingdraft/detail'
import {calcMarket, saveCalcLogs, getDefaultPricingParam, getCalendar} from '@/api/calc/otcOption/calc'
import {insertTrade, updateTrade} from '@/api/trade/otcoptiontrade'
import {onActivated} from '@vue/runtime-core'
import {calcTrade4OtcOptionByPage, queryTradeOption4OtcOptionByPage, deleteTrade} from '@/api/trade/tradebalance'
import {getToken} from '@/utils/auth'
import {calcAnnualizedByTerminationPaymentDate} from '@/utils/util'

import {ElMessageBox} from 'element-plus'
import {reject} from 'lodash'
import {isEqualNum, isNotVoid} from "../../../utils/util";

const OptionList = ref([])
const status = ref('insert')
const drawer2 = ref(false)
const direction = ref('rtl')
const radio1 = ref('Option 1')
const handleClose = (() => {
  ElMessageBox.confirm('Are you sure you want to close this?')
      .then(() => {
        done()
      })
      .catch(() => {
        // catch error
      })
})

const uploadType = ref(null)

const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: {Authorization: 'Bearer ' + getToken()},
  newurl: '',
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/pricing/trade/uploadOtcOptionTradeFile',
})


function cancelClick() {
  drawer2.value = false
}

function confirmClick() {
  ElMessageBox.confirm(`Are you confirm to chose ${radio1.value} ?`)
      .then(() => {
        drawer2.value = false
      })
      .catch(() => {
        // catch error
      })
}


const {proxy} = getCurrentInstance()

const {
  callPut,
  M_TYPE,
  A_TYPE,
  CURRENCY,
  optionType,
  priceType,
  exerciseType,
  tradeType,
  optionTypePp,
  optionStatus,
  durationStatus,
  payDirection,
  simpleTradeType,
} = proxy.useDict('callPut', 'M_TYPE', 'A_TYPE', 'CURRENCY', 'optionType', 'optionTypePp', 'priceType', 'exerciseType', 'tradeType', 'optionStatus', 'payDirection', 'durationStatus', 'simpleTradeType')

const tradeList = ref([])
const open = ref(false)
const disableFlag = ref(true)
const simpleOpen = ref(false)
const simpleType = ['LongOpen', 'LongClose', 'ShortClose', 'ShortOpen']
const tradeTitle = '场内交易'
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const selectRows = reactive({
  data: []
})
//索引
const indexs = ref([])
//数据
const rows = ref([])

const single = ref(true)
const single2 = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const dateRange = ref([])
const screenHeight = ref(document.documentElement.clientHeight - 300 + 'px')
const calTime = ref(null)
const isCalc = ref(false)
const router = useRouter()
const InstrumentDialogVisible = ref(false)
const InstrumentDialogInstrument = reactive({})

const fileName = ref('')
const fileType = ref('')

const data = reactive({
  tradeFrom: {
    amountDirection: '1',
    feeDirection: '1'
  },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    iCodeCond: undefined,
    iCodes: undefined,
    tradeIds: undefined,
    optionTypes: undefined,
    instruments: undefined,
    tradeDate1: undefined,
    tradeDate2: undefined,
    partyIds: undefined,
    accIds: undefined,
    priceType: 'DP_CLOSE',
    begDate1: undefined,
    begDate2: undefined,
    endDate1: undefined,
    endDate2: undefined,
    calcDate: proxy.getSysDate(),
    eventStatuss: undefined,
    payDirection: '',
    exerciseType: ''
  },
  UpLoadFilesLength: 0,
  UpLoadAllFilesLength: 0
})
const openDetailInsert = () => {
  instrument2TradeFrom.data = {
    iCode: '',
    accId: '',
    partyId: '',
    margin: '',
    amount: '',
    tradeDate: proxy.$moment(new Date()).format('YYYY-MM-DD'),
    remark: '',
    fee: '',
    feeDirection: '',
    setDate: '',
    marginDirection: '',
    extTradeId: '',
    frontFee: '',
    feeYear: '1',
    frontFeeYear: '1',
    frontFeePaydate: '',
    terminateDate: '',
    terminateFee: '0',
    version:''
  }
  status.value = 'insert'
  instruments.length = 0;
  drawer2.value = true;
}
const openDetailUpdate = () => {
  drawer2.value = true
  status.value = 'update'
  let {
    iCode, accId, partyId, amount, tradeDate, remark, feeDirection, setDate, marginDirection, extTradeId,
    frontFee,
    frontFeePaydate,
    terminateDate,
    terminateFee,
      version
  } = rows.value[0]
  instrument2TradeFrom.data = {
    iCode, accId, partyId, amount, tradeDate, remark, feeDirection, setDate, marginDirection, extTradeId,
    frontFee,
    frontFeePaydate,
    terminateDate,
    terminateFee,
    version
  }
  instrument2TradeFrom.data.marginDirection = Number(rows.value[0].margin) > 0 ? "1" : "-1"
  if (Math.abs(rows.value[0].margin) == 0) {
    instrument2TradeFrom.data.marginDirection = '';
  }
  instrument2TradeFrom.data.margin = Math.abs(rows.value[0].margin)
  instrument2TradeFrom.data.feeDirection = Number(rows.value[0].fee) > 0 ? "1" : "-1"
  if (Math.abs(rows.value[0].fee) == 0) {
    instrument2TradeFrom.data.feeDirection = '';
  }
  instrument2TradeFrom.data.fee = Math.abs(rows.value[0].frontOptionFee)
  instrument2TradeFrom.data.feeRate = rows.value[0].frontOptionFeeRate
  instrument2TradeFrom.data.feeYear = rows.value[0].frontOptionFeeYear

  instrument2TradeFrom.data.frontFeeDirection = Number(rows.value[0].frontFee) > 0 ? "1" : "-1"
  if (Math.abs(rows.value[0].frontFee) == 0) {
    instrument2TradeFrom.data.frontFeeDirection = '';
  }
  instrument2TradeFrom.data.frontFee = Math.abs(rows.value[0].frontFee)
  instrument2TradeFrom.data.frontFeeRate = rows.value[0].frontFeeRate
  instrument2TradeFrom.data.frontFeeYear = rows.value[0].frontFeeYear
  instrument2TradeFrom.data.version = rows.value[0].version
  if (rows.value.length > 0) {
    let {pForm, pFormPricing, pFormInstrument, tradeId, productType, pFormResult} = rows.value[0]
    instruments.length = 0
    var ele = {
      index: 0,
      flag: true,
      optionType: String(productType).toLowerCase(),
      calcPricingParam: JSON.parse(String(pFormPricing)) || {},
      result: {},
      formData: Object.assign({}, JSON.parse(String(pFormInstrument))),
      cfgId: calcPricingParam.cfgId
    }
    ele.index = index
    instruments.push(ele)
    index++
  }
}
const {queryParams, tradeFrom} = toRefs(data)
watch(() => queryParams.value.begDate1, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.begDate2)) {
    let a = proxy.$moment(newVal)
    let b = proxy.$moment(queryParams.value.begDate2)
    if (a > b) {
      queryParams.value.begDate2 = newVal
    }
  }
})
watch(() => queryParams.value.begDate2, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.begDate1)) {
    let b = proxy.$moment(newVal)
    let a = proxy.$moment(queryParams.value.begDate1)
    if (a > b) {
      queryParams.value.begDate1 = newVal
    }
  }
})
watch(() => queryParams.value.endDate1, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.endDate2)) {
    let a = proxy.$moment(newVal)
    let b = proxy.$moment(queryParams.value.endDate2)
    if (a > b) {
      queryParams.value.endDate2 = newVal
    }
  }
})
watch(() => queryParams.value.endDate2, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.endDate1)) {
    let b = proxy.$moment(newVal)
    let a = proxy.$moment(queryParams.value.endDate1)
    if (a > b) {
      queryParams.value.endDate1 = newVal
    }
  }
})
watch(() => queryParams.value.tradeDate1, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.tradeDate2)) {
    let a = proxy.$moment(newVal)
    let b = proxy.$moment(queryParams.value.tradeDate2)
    if (a > b) {
      queryParams.value.tradeDate2 = newVal
    }
  }
})
watch(() => queryParams.value.tradeDate2, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.tradeDate1)) {
    let b = proxy.$moment(newVal)
    let a = proxy.$moment(queryParams.value.tradeDate1)
    if (a > b) {
      queryParams.value.tradeDate1 = newVal
    }
  }
})

/** 查询列表 */
function getTradeList() {
  rows.value = []
  loading.value = true
  if (proxy.isNotVoid(router.currentRoute.value.query)) {
    queryParams.value.instruments = router.currentRoute.value.query.instrument
    queryParams.value.iCodes = router.currentRoute.value.query.iCodes
  }
  let params = proxy.lsh.cloneDeep(queryParams.value)
  params.instruments = proxy.lsh.join(params.instruments, '|');
  params.accIds = proxy.lsh.join(params.accIds, ',');
  params.eventStatuss = proxy.lsh.join(params.eventStatuss, ',');
  params.optionTypes = proxy.lsh.join(params.optionTypes, ',');
  params.partyIds = proxy.lsh.join(params.partyIds, ',');
  queryTradeOption4OtcOptionByPage(params).then(response => {
    tradeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

onActivated(() => {
  //解决跳转页面不刷新
  getTradeList()
})


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  if (proxy.isNotVoid(router.currentRoute.value.query)) {
    router.currentRoute.value.query = null
    queryParams.value.instrument = null
    queryParams.value.iCodes = null
  }
  queryParams.value.tradeIds = null
  getTradeList()
}

function beforeUpload() {
  return new Promise((resolve, reject) => {
    //拼接上传URL
    upload.newurl = upload.url + "?uploadType=" + uploadType.value;
    nextTick(() => resolve())
  })
}

// 删除交易
function handleDelete() {
  proxy.$modal
      .confirm('是否确认删除合约编号为 "' + rows.value[0].iCode + '"的数据项？')
      .then(function () {
        return deleteTrade(rows.value[0])
      })
      .then(() => {
        getTradeList()
        proxy.$modal.msgSuccess('删除成功')
      })
}

/** 计算 */
function handleCalc() {
  queryParams.value.tradeIds = null
  var tradeIdsArry = []
  if (rows.value.length > 0) {
    rows.value.forEach(element => {
      tradeIdsArry.push(element.tradeId)
    })
    queryParams.value.tradeIds = JSON.stringify(tradeIdsArry)
  }
  queryParams.value.pageNum = 1
  isCalc.value = true
  calTime.value = '开始计算: ' + proxy.getCurrTime('YYYY-mm-dd HH:MM:SS', new Date())
  calcTrade4OtcOptionByPage(queryParams.value).then(response => {
    getTradeList()
    isCalc.value = false
    calTime.value = '刷新时间: ' + proxy.getCurrTime('YYYY-mm-dd HH:MM:SS', new Date())
  })

}

/** 跳转定价页面 */
function handlePricing() {

  if (rows.value.length > 0) {
    let {pForm, pFormPricing, pFormInstrument, tradeId, productType, pFormResult} = rows.value[0]
    router.push({
      path: '/calc/OtcOptionRef/index/' + tradeId,
      // name: 'CALC',
      query:
          {
            "dataId": '交易重放'+tradeId,
            'pForm': pForm,
            'pFormInstrument': pFormInstrument,
            'pFormPricing': pFormPricing,
            'productType': productType,
            'pFormResult': pFormResult,
            title: '交易重放' + tradeId,
            showTitleDetail: '交易重放' + tradeId
          },
    })
  }
}


function TradeBalanceTableSelect(selection) {
  if (selection.length == 0) {
    indexs.value = []
  } else {
    indexs.value = selection.map(item => item.index)
    rows.value = selection.map(item => item)
  }
  single.value = selection.length != 1
  single2.value = !selection.length
  multiple.value = !selection.length
  if (selection.length == 1) {
    return
  }
  if (selection.length != 1) {

  }

}

function formartTradeType(row, column, cellValue) {
  let fmtValue = '*'
  proxy.lsh.map(tradeType.value, function (o) {
    if (o.value == cellValue) {
      fmtValue = o.label
    }
  })
  return fmtValue
}

/** 导出按钮操作 */
function handleExport() {
  if (proxy.isNotVoid(router.currentRoute.value.query)) {
    queryParams.value.instruments = router.currentRoute.value.query.instrument
    queryParams.value.iCodes = router.currentRoute.value.query.iCodes
  }
  let params = proxy.lsh.cloneDeep(queryParams.value)
  params.instruments = proxy.lsh.join(params.instruments, '|');
  params.accIds = proxy.lsh.join(params.accIds, ',');
  params.eventStatuss = proxy.lsh.join(params.eventStatuss, ',');
  params.optionTypes = proxy.lsh.join(params.optionTypes, ',');
  params.partyIds = proxy.lsh.join(params.partyIds, ',');
  proxy.download('/pricing/trade/exportTrade.action', {
    ...params
  }, `期权簿记${proxy.getCurrTime('YYYYmmddHHMMSS', new Date())}.xlsx`)
}

/** 导出按钮操作 */
function handleExportAll() {
    if (proxy.isNotVoid(router.currentRoute.value.query)) {
        queryParams.value.instruments = router.currentRoute.value.query.instrument
        queryParams.value.iCodes = router.currentRoute.value.query.iCodes
    }
    let params = {};
    var tradeIdsArry = []
    if (rows.value.length > 0) {
        rows.value.forEach(element => {
            tradeIdsArry.push(element.tradeId)
        })
        params.tradeIds = JSON.stringify(tradeIdsArry);
    } else {
        params = proxy.lsh.cloneDeep(queryParams.value);
        params.instruments = proxy.lsh.join(params.instruments, '|');
        params.accIds = proxy.lsh.join(params.accIds, ',');
        params.eventStatuss = proxy.lsh.join(params.eventStatuss, ',');
        params.optionTypes = proxy.lsh.join(params.optionTypes, ',');
        params.partyIds = proxy.lsh.join(params.partyIds, ',');
    }
    proxy.download('/pricing/trade/exportTrade.action', Object.assign({
        ...params
    }, {pageSize: ''}), `期权簿记${proxy.getCurrTime('YYYYmmddHHMMSS', new Date())}.xlsx`)
}

function handleDbclick(row, column, event) {
    if (simpleType.includes(row.tradeType)) {
        tradeFrom.value = row
        tradeFrom.value.instrumenId = row.uICode + ',' + row.aType + ',' + row.mType
        simpleOpen.value = true
        if (tradeFrom.value.amount < 0) {
            tradeFrom.value.amountDirection = '-1'
            tradeFrom.value.amount = Math.abs(tradeFrom.value.amount)
        } else if (tradeFrom.value.amount == 0) {
            tradeFrom.value.amountDirection = '';
        } else {
            tradeFrom.value.amountDirection = '1'
        }
        if (tradeFrom.value.fee < 0) {
            tradeFrom.value.feeDirection = '-1'
            tradeFrom.value.fee = Math.abs(tradeFrom.value.fee)
        } else if (tradeFrom.value.fee == 0) {
            tradeFrom.value.feeDirection = '';
        } else {
            tradeFrom.value.feeDirection = '1'
        }

  } else {
    let {
      pForm,
      pFormPricing,
      pFormInstrument,
      draftName,
      optionType,
      partyId,
      setDate,
      margin,
      id,
      pFormResult,
      productType,
      remark,
      fee,
      amount,
      tradeDate,
      tradeId,
      accId,
      iCode,
      extTradeId,
      frontFee,
      frontFeeYear,
      frontFeeRate,
      frontOptionFeeYear,
      frontOptionFeeRate,
      frontOptionFee,
      frontFeePaydate,
      terminateDate,
      terminateFee,
        version
    } = row

    let amountDirection = margin < 0 ? '-1' : '1';
    if (margin == 0) {
      amountDirection = '';
    }
    let feeDirection = fee < 0 ? '-1' : '1'
    if (fee == 0) {
      feeDirection = '';
    }
    let frontFeeDirection = frontFee < 0 ? '-1' : '1'
    if (frontFee == 0) {
      frontFeeDirection = '';
    }

    InstrumentDialogInstrument.data = {
      pForm,
      pFormPricing,
      pFormInstrument,
      draftName,
      optionType,
      id,
      iCode,
      partyId,
      setDate,
      pFormResult,
      remark,
      amount: Math.abs(margin),
      tradeDate,
      tradeId,
      accId, amountDirection, feeDirection, frontFeeDirection,
      extTradeId,
      frontFeePaydate,
      terminateDate,
      terminateFee,
      version
    }
    InstrumentDialogInstrument.data.optionType = productType
    InstrumentDialogInstrument.data.fee = Math.abs(frontOptionFee)
    InstrumentDialogInstrument.data.feeRate = frontOptionFeeRate
    InstrumentDialogInstrument.data.feeYear = frontOptionFeeYear

    InstrumentDialogInstrument.data.frontFee = Math.abs(frontFee)
    InstrumentDialogInstrument.data.frontFeeRate = frontFeeRate
    InstrumentDialogInstrument.data.frontFeeYear = frontFeeYear
    if (isEqualNum(0, InstrumentDialogInstrument.data.frontFeeRate) && !isEqualNum(0, InstrumentDialogInstrument.data.frontFee)) {
      let parseForm = JSON.parse(pFormInstrument)
      let annualized = calcAnnualizedByTerminationPaymentDate(parseForm)
      let notional = parseForm.notional
      if ('1' == InstrumentDialogInstrument.data.frontFeeYear) {
        InstrumentDialogInstrument.data.frontFeeRate = Number(InstrumentDialogInstrument.data.frontFee / notional / annualized * 100).toFixed(2)
      } else {
        InstrumentDialogInstrument.data.frontFeeRate = Number(InstrumentDialogInstrument.data.frontFee / notional * 100).toFixed(2)
      }
    }
    if (isEqualNum(0, InstrumentDialogInstrument.data.feeRate) && !isEqualNum(0, InstrumentDialogInstrument.data.fee)) {
      let parseForm = JSON.parse(pFormInstrument)
      let annualized = calcAnnualizedByTerminationPaymentDate(parseForm)
      let notional = parseForm.notional
      if ('1' == InstrumentDialogInstrument.data.feeYear) {
        InstrumentDialogInstrument.data.feeRate = Number(InstrumentDialogInstrument.data.fee / notional / annualized * 100).toFixed(2)
      } else {
        InstrumentDialogInstrument.data.feeRate = Number(InstrumentDialogInstrument.data.fee / notional * 100).toFixed(2)
      }
    }
    if (!isEqualNum(0, InstrumentDialogInstrument.data.feeRate) && isEqualNum(0, InstrumentDialogInstrument.data.fee)) {
      let parseForm = JSON.parse(pFormInstrument)
      let annualized = calcAnnualizedByTerminationPaymentDate(parseForm)
      let notional = parseForm.notional
      if ('1' == InstrumentDialogInstrument.data.feeYear) {
        InstrumentDialogInstrument.data.fee = Number(notional * InstrumentDialogInstrument.data.feeRate / 100 * annualized).toFixed(2)
      } else {
        InstrumentDialogInstrument.data.fee = Number(notional * InstrumentDialogInstrument.data.feeRate / 100).toFixed(2)
      }
    }
    InstrumentDialogVisible.value = true
  }
}

function openDetail(index, row) {
  handleDbclick(row)
}

function closeInstrumentDialog() {
  InstrumentDialogVisible.value = false
  InstrumentDialogInstrument.data = {}
  instrument2TradeFrom.data = {}
}


onMounted(() => {
  setTimeout(() => {
    loading.value = false
  }, 300)
  getOptionList().then(res => {
    OptionList.value = res;
  });
  window.onresize = function temp() {
    screenHeight.value = document.documentElement.clientHeight - 80 + 'px;'
  }
})
const instrument2TradeFrom = reactive({
  data: {
    iCode: '',
    accId: '',
    partyId: '',
    margin: '',
    amount: '',
    tradeDate: proxy.$moment(new Date()).format('YYYY-MM-DD'),
    remark: '',
    fee: '',
    feeRate: '',
    frontFee: '',
    frontFeeRate: '',
    feeYear: '1',
    frontFeeYear: '1',
    feeDirection: '',
    setDate: '',
    marginDirection: '',
    version: ''
  }
})
const calcPricingParam = reactive({
  valueDate: proxy.$moment(new Date()).format('YYYY-MM-DD'),
  cfgId: '',
})

let instruments = reactive([])
let index = 0


const dialog2DocumentFormRules = {
  iCode: [{required: true, message: ' ', trigger: 'change'}],
  accId: [{required: true, message: ' ', trigger: 'change'}],
  margin: [{required: false, message: ' ', trigger: 'change'}],
  amount: [{required: true, message: ' ', trigger: 'change'}],
  tradeDate: [{required: true, message: ' ', trigger: 'change'}],
  marginDirection: [{required: true, message: ' ', trigger: 'change'}],
  setDate: [{required: false, message: ' ', trigger: 'change'}],
  feeDirection: [{required: true, message: ' ', trigger: 'change'}],
  remark: [{required: false, message: ' ', trigger: 'change'}],
}
watch(() => calcPricingParam.cfgId, (nv, ov) => {
  if (nv != ov) {
    for (let instrument of instruments) {
      instrument.cfgId = nv
    }
  }
})

function submit(data, index, flag) {
  calcMarket(data, index, flag).then(response => {
    if (response.errorCode != 0) {
      proxy.$modal.msgError('计算出错！\n' + response.errorMsg)
    } else {
      proxy.$modal.msgSuccess('计算成功！')
      let result = response.result
      //gammacash = Gamma*标的现价^2/100
      //Deltacash=Delta*标的现价
      //"npv%": 100*result.contract.npv/me.ownerCt.ownerCt.instrumentPanel.getInstrument().termsheet.notional+"",
      let other = {
        "npvPercentage": formartFormP4(100 * result.contract.npv / data.instrument.termsheet.notional),
        "yearnpvPercentage": formartFormP4(100 * result.contract.npv / data.instrument.termsheet.notional / calcAnnualizedByTerminationPaymentDate(data.calcInstrumentForm)),
        'gammacash': formartFormP4(response.result.contract.gamma * response.result.contract.spotPrice * response.result.contract.spotPrice / 100),
        'deltacash': formartFormP4(response.result.contract.delta * response.result.contract.spotPrice)
      }
      index = instruments.map(item => item.index).indexOf(index)
      instruments[index].result = Object.assign(response.result.contract, other)
      instruments[index].result['status'] = 1
    }
  })
}

function submitAll() {
  let calc = []
  for (let instrument of instruments) {
    let refIndex = 'instrument' + instrument.index
    proxy.$refs[refIndex][0].calc('All')
  }
}

const getDefaultCfg = (optionJson, index) => {
  if (optionJson.instrument.termsheet.underlyerIds.length > 0 && optionJson.instrument.termsheet.underlyerIds[0] != '') {
    getDefaultPricingParam(optionJson).then(response => {
      if (response.errorCode != 0) {

      } else {
        let {underlyingPricingParams, discount, calcPPCode} = response.result.calcPricingParam
        let {spotQuoteType, dividend, volSurface} = underlyingPricingParams[0]
        let ppcfg = {
          calcPPCode: calcPPCode,
          spotQuoteType: spotQuoteType,
          dividend: dividend,
          discount: discount,
          volSurface: volSurface
        }
        index = instruments.map(item => item.index).indexOf(index)
        instruments[index].calcPricingParam = ppcfg
        return response.result.calcPricingParam
      }
    })
  }
}

function del(current) {
  current = instruments.map(item => item.index).indexOf(current)
  instruments.splice(current, 1)
}

function delAll() {
  instruments.length = 0
}

function copy(current) {
  setformData(current)
  current = instruments.map(item => item.index).indexOf(current)
  let cloneDeep = proxy.lsh.cloneDeep(instruments[current])
  var ele = {
    index: 0,
    optionType: cloneDeep.optionType,
    result: {},
    formData: cloneDeep.formData,
    calcPricingParam: cloneDeep.calcPricingParam || {}
  }
  ele.index = index
  //复制form 数据
  instruments.push(ele)
  index++
}

function createNode(optionType) {
  //先清空已有的面板
  if (getInstrument(optionType)) {
    instruments.length = 0
    var ele = {
      index: 0,
      optionType: optionType,
      calcPricingParam: {},
      result: {},
      cfgId: calcPricingParam.cfgId
    }
    ele.index = index
    instruments.push(ele)
    window.dispatchEvent(new Event('resize')) // 触发window的resize事件
    index++
  }
}

function setformData(current) {
  //设置定价参数
  setPriceParam(current)
  current = instruments.map(item => item.index).indexOf(current)
  let refIndex = 'instrument' + instruments[current].index
  instruments[current].formData = proxy.$refs[refIndex][0].getFormData()
}

function setPriceParam(current) {
  //设置定价参数
  current = instruments.map(item => item.index).indexOf(current)
  let refIndex = 'instrument' + instruments[current].index
  instruments[current].calcPricingParam = proxy.$refs[refIndex][0].getCalcPriceParam()
  return
}

function saveTrade() {
  if (instruments.length > 0) {
    let refIndex = 'instrument' + instruments[0].index
    proxy.$refs[refIndex][0].getInstrumentJson().then((res) => {
      if (Boolean(res)) {
        // OpenDialog2Document(res)
        save2Document(res)
      }
    })
  } else {
    proxy.$modal.msgWarning('至少录入一个期权结构')
  }
}

function save2Document(instrument2TradeData) {
  let instrument = instrument2TradeData.otcOption.instrument
  let calcInstrumentForm = instrument2TradeData.calcInstrumentForm
  let calcPricingForm = instrument2TradeData.calcPricingForm
  let calcResultForm = instrument2TradeData.calcResultForm
  proxy.$refs['dialog2DocumentForm'].validate(valid => {
    if (valid) {
      //如果金额不为0或空 则首付方向必输
      if (isNotVoid(instrument2TradeFrom.data.margin) && instrument2TradeFrom.data.margin > 0 && !isNotVoid(instrument2TradeFrom.data.marginDirection)) {
        proxy.$modal.alertWarning('请设置保证金收付方向!')
        return
      }
      if (isNotVoid(instrument2TradeFrom.data.fee) && instrument2TradeFrom.data.fee > 0 && !isNotVoid(instrument2TradeFrom.data.feeDirection)) {
        proxy.$modal.alertWarning('请设置期权费收付方向!')
        return
      }

      if (isNotVoid(instrument2TradeFrom.data.fee) && instrument2TradeFrom.data.fee > 0 && !isNotVoid(instrument2TradeFrom.data.setDate)) {
        proxy.$modal.alertWarning('请设置期权费收付日期!')
        return
      }
      if (isNotVoid(instrument2TradeFrom.data.frontFee) && instrument2TradeFrom.data.frontFee > 0 && !isNotVoid(instrument2TradeFrom.data.frontFeeDirection)) {
        proxy.$modal.alertWarning('请设置前端费收付方向!')
        return
      }

      if (isNotVoid(instrument2TradeFrom.data.frontFee) && instrument2TradeFrom.data.frontFee > 0 && !isNotVoid(instrument2TradeFrom.data.frontFeePaydate)) {
        proxy.$modal.alertWarning('请设置前端费费收付日期!')
        return
      }
      /*处理期权费*/
      instrument.termsheet["legs"].push({
        "legId": "leg02",
        "payDirection": Number(instrument2TradeFrom.data.feeDirection)
        //  instrument2TradeFrom.data.fee * Number(instrument2TradeFrom.data.feeDirection)
      })
      instrument.termsheet["customLegs"].push({
        "legId": "leg02",
        "productType": "Premium",
        "paymentDate": instrument2TradeFrom.data.setDate,
        "paymentConv": "NONE",
        "paymentAmount": instrument2TradeFrom.data.fee,
        "paymentCurrency": "CNY"
      })
      var trade = {
        // 交易要素
        extTradeId: instrument2TradeFrom.data.extTradeId,
        optionType: calcInstrumentForm.optionType,
        frontFee: instrument2TradeFrom.data.frontFee * Number(instrument2TradeFrom.data.frontFeeDirection),
        frontFeeRate: instrument2TradeFrom.data.frontFeeRate,
        frontFeeYear: instrument2TradeFrom.data.frontFeeYear,
        frontFeePaydate: instrument2TradeFrom.data.frontFeePaydate,
        frontOptionFee: instrument2TradeFrom.data.fee * Number(instrument2TradeFrom.data.feeDirection),
        frontOptionFeeRate: instrument2TradeFrom.data.feeRate,
        frontOptionFeeYear: instrument2TradeFrom.data.feeYear,
        frontOptionFeePaydate: instrument2TradeFrom.data.setDate,
        terminateDate: instrument2TradeFrom.data.terminateDate,
        terminateFee: instrument2TradeFrom.data.terminateFee,
        tradeType: Boolean(instrument.termsheet.legs) ?
            (instrument.termsheet.legs[0].payDirection == "-1" ? "OtcOptionSell" : "OtcOptionBuy")
            : (instrument.termsheet.payDirection == "-1" ? "OtcOptionSell" : "OtcOptionBuy"),
        volume: instrument.termsheet.notional,
        spotPrice: Boolean(instrument.termsheet.customLegs) ? instrument.termsheet.customLegs[0].underlyers[0].spotPrice : instrument.termsheet.issuePrice,
        aType: 'CTM',
        mType: 'NONE',
        currency: instrument.termsheet.notionalCurrency,
        /* trade.extInfo = Ext.encode(me.extInfoFieldSet.getValue());*/
        tradeDate: instrument2TradeFrom.data.tradeDate,
        accId: instrument2TradeFrom.data.accId,
        partyId: instrument2TradeFrom.data.partyId,
        iCode: instrument2TradeFrom.data.iCode,
        // trade.setDate : me.dateFieldFeePayDate.getRawValue(),
        margin: instrument2TradeFrom.data.margin * Number(instrument2TradeFrom.data.marginDirection),
        fee: instrument2TradeFrom.data.fee * Number(instrument2TradeFrom.data.feeDirection),
        setDate: instrument2TradeFrom.data.setDate,
        // trade.amount : me.cbxPayDirection.getValue() * me.amtFieldFee.getAmount(),
        // trade.currency : me.amtFieldFee.getCurrency(),
        remark: instrument2TradeFrom.data.remark,
        // trade.relatedProducts : me.relatedProducts.getValue(),
        // trade.txtSupAgrId : me.txtSupAgrId.getValue(),
        ocFlag: 'O',
        version: instrument2TradeFrom.data.version,
        calcInstrumentForm: calcInstrumentForm,
        calcPricingForm: calcPricingForm,
        calcResultForm: calcResultForm,
        // 金融工具要素
        instrumentInfo: {
          pCalc: JSON.stringify(instrument),
          instrumentId: instrument.termsheet.underlyerIds[0],
          currency: instrument.termsheet.notionalCurrency,
          pNotional: 1,
          country: 'CN',
          qType: 'Dp',
          pName: instrument.productType,
          pType: instrument.productType,
          pClass: instrument.productType,
          issueDate: instrument.termsheet.effectiveDate,
          maturityDate: instrument.termsheet.terminationDate,
          settlementType: 'C',
          // calendar: calendar,
          bizdayConvertion: instrument.termsheet.effectiveDateConv
        }
      }
      loading.value = true
      if (status.value == 'insert') {
        insertTrade(trade).then((res) => {
          if (res.success) {
            proxy.$modal.msgSuccess('保存成功！')
            proxy.$refs['dialog2DocumentForm'].resetFields()
          } else {
            proxy.$modal.msgError('出错！\n' + res.msg)
          }
          loading.value = false
          getTradeList()
        })
      } else if (status.value == 'update') {
        trade['tradeId'] = rows.value[0].tradeId
        updateTrade(trade).then((res) => {
          if (res.success) {
            proxy.$modal.msgSuccess('保存成功！')
            proxy.$refs['dialog2DocumentForm'].resetFields()
            drawer2.value = false
            getTradeList()
          } else {
            proxy.$modal.msgError('出错！\n' + res.msg)
          }
          loading.value = false
        })
      }

    }
  })

}

function changeToTitle(type) {
  switch (type) {
    case 'Vanilla':
      return '香草期权'
    case 'Digital':
      return '二元期权'
    case 'DoubleDigital':
      return '双层二元'
    case 'MultiDigital':
      return '三层阶梯'
    case 'Touch':
      return '触碰期权'
    case 'SingleSharkFin':
      return '单鲨期权'
    case 'DoubleShark':
      return '双鲨期权'
    case 'DoubleBarrier':
      return '双障碍期权'
    case 'RangeAccrual':
      return '区间累计期权'
    case 'BasicSnowball':
      return '保本雪球'
    default:
      return type
  }
}


function handleImport(type) {
  uploadType.value = type
  upload.title = changeToTitle(type) + '导入'
  upload.open = true
}
// 上传文件时是需要改回el-upload__input的webkitdirectory属性
function uploadFile() {
  nextTick(() => {
    document.getElementsByClassName(
      "el-upload__input"
    )[0].webkitdirectory = false;
  })
}

// 上传文件夹是需要修改el-upload__input的webkitdirectory属性
function uploadFolder() {
  nextTick(() => {
    document.getElementsByClassName(
      "el-upload__input"
    )[0].webkitdirectory = true;
  })
}

// 下载模板
function downTemplate() {
  var tempFileName = ''
  switch (uploadType.value) {
    case 'Vanilla':
      tempFileName = '期权簿记香草期权导入模板.xlsx'
      break
    case 'Digital':
      tempFileName = '期权簿记二元期权导入模板.xlsx'
      break
    case 'DoubleDigital':
      tempFileName = '期权簿记双层二元导入模板.xlsx'
      break
    case 'MultiDigital':
      tempFileName = '期权簿记三层阶梯导入模板.xlsx'
      break
    case 'Touch':
      tempFileName = '期权簿记触碰期权导入模板.xlsx'
      break
    case 'SingleSharkFin':
      tempFileName = '期权簿记单鲨期权导入模板.xlsx'
      break
    case 'DoubleShark':
      tempFileName = '期权簿记双鲨期权导入模板.xlsx'
      break
    case 'DoubleBarrier':
      tempFileName = '期权簿记双障碍期权导入模板.xlsx'
      break
    case 'RangeAccrual':
      tempFileName = '期权簿记区间累计期权导入模板.xlsx'
      break
    case 'BasicSnowball':
      a
      tempFileName = '期权簿记保本雪球导入模板.xlsx'
      break
    case 'Option':
      tempFileName = '期权簿记Option二元导入模板.csv'
      break
    case 'Must':
      tempFileName = '期权簿记Must单鲨导入模板.csv'
      break
    default :
      proxy.$modal.msgWarning('不支持该期权结构的模板下载')
      return false
  }

  proxy.download('pricing/trade/downloadFile.action', Object.assign({
    fileName, fileType,
  }, {fileName: tempFileName, fileType: 'xls,xlsx', businType: uploadType.value}), tempFileName)

}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件上传成功处理 proxy.$refs['uploadRef'].uploadFiles 会记录每个文件返回的结果*/
const handleFileSuccess = (response, file, fileList) => {
  if (proxy.$refs['uploadRef'].uploadFiles) {
        let length = proxy.$refs.uploadRef.uploadFiles.length
        data.UpLoadFilesLength ++  // 全局变量，用来计算upLoadSuccess方法调用次数
        if (data.UpLoadFilesLength == length) {
            data.UpLoadFilesLength = 0  // 如果方法调用的次数和文件列表的长度相同，说明所有文件都上传完毕，将该全局变量置0
            resErrorStr() // 该函数处理每个文件上传错误情况下response拼接
        }
    }
}
// 处理批量上传文件的返回信息
function resErrorStr() {
  if (proxy.$refs['uploadRef'].uploadFiles) { // 如果存在这个值
    let length = proxy.$refs.uploadRef.uploadFiles.length
    let failedNum = 0 //上传失败的文件数量
    let filesList = proxy.$refs['uploadRef'].uploadFiles.slice()
    let UpLoadAllErrorStr = '' // 错误信息拼接变量
    for (let i = 0; i < filesList.length; i++) {
      if (filesList[i].response) {
        if (filesList[i].response.success == false) { // 如果该文件上传后返回的状态值不是成功，则说明该文件上传错误
            failedNum ++
            UpLoadAllErrorStr += `${filesList[i].name} ${filesList[i].response.msg}<br/>`
        }
      }
    }
    let successNum = length - failedNum
    UpLoadAllErrorStr = '总导入数据：'+length+'笔；成功：'+successNum+'笔；失败：'+failedNum+'笔；<br/>' + UpLoadAllErrorStr

    proxy.$alert('<div style=\'overflow: auto;white-space: pre ;max-height: 70vh;padding: 10px 20px 0;\'>' + UpLoadAllErrorStr + '</div>', '导入结果', {dangerouslyUseHTMLString: true})

    proxy.$refs['uploadRef'].uploadFiles = [] // 调用完成之后将值置空，防止再次上传将上次结果也记录下来
    upload.open = false
    upload.isUploading = false
    proxy.$refs['uploadRef'].clearFiles()
    getTradeList();
  }
}
//上传文件超过数量回调
function exceedLimit() {
  proxy.$alert('<div style=\'overflow: auto;overflow-x: hidden;white-space: pre ;max-height: 70vh;padding: 10px 20px 0;\'>' + '上传文件数量超过数量限制' + '</div>', '上传失败', {dangerouslyUseHTMLString: true})
}

//取消上传操作，清空文件
function cancelUpload() {
  upload.open = false
  upload.isUploading = false
  proxy.$refs['uploadRef'].clearFiles()
}


/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs['uploadRef'].submit()
}

const onfrontFeeRateChange = () => {
  let refIndex = 'instrument' + instruments[0].index
  proxy.$refs[refIndex][0].getInstrumentJson().then((instrument2TradeData) => {
    if (Boolean(instrument2TradeData)) {
      let annualized = calcAnnualizedByTerminationPaymentDate(instrument2TradeData.calcInstrumentForm)
      let notional = instrument2TradeData.calcInstrumentForm.notional
      if ('1' == instrument2TradeFrom.data.frontFeeYear) {
        instrument2TradeFrom.data.frontFee = Number(notional * instrument2TradeFrom.data.frontFeeRate / 100 * annualized)
      } else {
        instrument2TradeFrom.data.frontFee = Number(notional * instrument2TradeFrom.data.frontFeeRate / 100)
      }
    }
  })

}
const onfrontFeeChange = () => {
  let refIndex = 'instrument' + instruments[0].index
  proxy.$refs[refIndex][0].getInstrumentJson().then((instrument2TradeData) => {
    if (Boolean(instrument2TradeData)) {
      let annualized = calcAnnualizedByTerminationPaymentDate(instrument2TradeData.calcInstrumentForm)
      let notional = instrument2TradeData.calcInstrumentForm.notional
      if ('1' == instrument2TradeFrom.data.frontFeeYear) {
        instrument2TradeFrom.data.frontFeeRate = Number(instrument2TradeFrom.data.frontFee / notional / annualized * 100)
      } else {
        instrument2TradeFrom.data.frontFeeRate = Number(instrument2TradeFrom.data.frontFee / notional * 100)
      }
    }
  })

}
const onFeeChange = () => {
  let refIndex = 'instrument' + instruments[0].index
  proxy.$refs[refIndex][0].getInstrumentJson().then((instrument2TradeData) => {
    if (Boolean(instrument2TradeData)) {
      let annualized = calcAnnualizedByTerminationPaymentDate(instrument2TradeData.calcInstrumentForm)
      let notional = instrument2TradeData.calcInstrumentForm.notional
      if ('1' == instrument2TradeFrom.data.feeYear) {
        instrument2TradeFrom.data.feeRate = Number(instrument2TradeFrom.data.fee / notional / annualized * 100)
      } else {
        instrument2TradeFrom.data.feeRate = Number(instrument2TradeFrom.data.fee / notional * 100)
      }
    }
  })

}
const onFeeRateChange = () => {
  let refIndex = 'instrument' + instruments[0].index
  proxy.$refs[refIndex][0].getInstrumentJson().then((instrument2TradeData) => {
    if (Boolean(instrument2TradeData)) {
      let annualized = calcAnnualizedByTerminationPaymentDate(instrument2TradeData.calcInstrumentForm)
      let notional = instrument2TradeData.calcInstrumentForm.notional
      if ('1' == instrument2TradeFrom.data.feeYear) {
        instrument2TradeFrom.data.fee = Number(notional * instrument2TradeFrom.data.feeRate / 100 * annualized)
      } else {
        instrument2TradeFrom.data.fee = Number(notional * instrument2TradeFrom.data.feeRate / 100)
      }
    }
  })

}

const getIndexRef = (index) => {
  return proxy.$refs['instrument' + index]
}
provide('getIndexRef', getIndexRef)
</script>

<style scoped>
.tradeCard {
  margin: 1rem 0.5rem 1rem 0.5rem;
  padding: 1rem;
  height: 100%;
}

.instrumentCard {
  margin: 1rem 0.5rem 1rem 0rem;
  padding: 1rem;
  height: 100%;
}

/deep/ .el-card__header {
  background-color: white;
  background-image: inherit;
}
</style>



